package com.health.mapp.impl;



import org.apache.log4j.Logger;

import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.health.commons.PropertiesService;
import com.health.mapp.bean.GetOSSTokenReq;
import com.health.mapp.bean.GetOSSTokenResp;
import com.health.mapp.bean.Header;
import com.health.mapp.utils.ResultCode;
import com.health.mapp.utils.StringUtils;

/**
 * 获取token
 * @author Administrator
 *
 */
public class GetOSSTokenImpl implements ActionInterface {

	private static Logger logger = Logger.getLogger(GetOSSTokenImpl.class);


	@Override
	public GetOSSTokenResp execute(Header header, Object reqBean)  {
		GetOSSTokenReq req = (GetOSSTokenReq) reqBean;
		GetOSSTokenResp _resp = new GetOSSTokenResp();
		

		  String accessKeyId = PropertiesService.getString("oss.accessKeyId").trim();
		  String accessKeySecret = PropertiesService.getString("oss.accessKeySecret").trim();
		  String  roleArn = PropertiesService.getString("oss.roleReadWrite").trim();
		  
		 

		 String roleSessionName = String.valueOf(req.getUserId());

		    
		    String policy1="{\n"+
	  "	\"Version\": \"1\",\n"+
	  "	\"Statement\": [\n"+
	  "		{\n"+
	  "			\"Effect\": \"Allow\",\n"+
	  "		    \"Action\": [\n"+
	  "		    	\"oss:ListObjects\",\n"+
	  "		    	\"oss:GetObject\"\n"+
	  "		    ],\n"+
	  "		    \"Resource\": [\n"+
	  "		    	\"acs:oss:*:*:shouer\",\n"+
	  "		   		\"acs:oss:*:*:shouer/*\"\n"+
	  "		    ]\n"+
	  "		},\n"+
	  "		{\n"+
	  "			\"Effect\": \"Allow\",\n"+
	  "			\"Action\": [\n"+
	  "				\"oss:AbortMultipartUpload\",\n"+
	  "				\"oss:PutObject\"\n"+
	  "			],\n"+
	  "			\"Resource\": [\n"+
	  "				\"acs:oss:*:*:shouer\",\n"+
	  "				\"acs:oss:*:*:shouer/*\"\n"+
	  "			]\n"+
	  "		}\n"+
	  "   ]\n"+
	  "}";
		    ProtocolType protocolType = ProtocolType.HTTPS;

		    try {
		      final AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret,
		              roleArn, roleSessionName, policy1, protocolType);
		      _resp.setAccessTime(StringUtils.getSysTimeYYMMDDHHMMSS());
		      _resp.setAccessId(response.getCredentials().getAccessKeyId());
		      _resp.setAccessSecret(response.getCredentials().getAccessKeySecret());
		      _resp.setoSSToken(response.getCredentials().getSecurityToken());
		      _resp.setExpiration(response.getCredentials().getExpiration());
		      logger.debug("Token explain");
		      logger.debug("Expiration: " + response.getCredentials().getExpiration());
		      logger.debug("Access Key Id: " + response.getCredentials().getAccessKeyId());
		      logger.debug("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
		      logger.debug("Security Token: " + response.getCredentials().getSecurityToken());
		    } catch (ClientException e) {
		    	logger.debug("Failed to get a federation token.");
		    	_resp.setErrorCode(ResultCode.OSS_TOKEN_CONNECT_ERROR);
		    	_resp.setErrorMsg(ResultCode.OSS_TOKEN_CONNECT_ERROR_NOTE);
		    } catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		
		    }
		    
		    return _resp;
	}


	static AssumeRoleResponse assumeRole(String accessKeyId,
			String accessKeySecret, String roleArn, String roleSessionName,
			String policy, ProtocolType protocolType) throws Exception {
			IClientProfile profile = DefaultProfile.getProfile(
					PropertiesService.getString("oss.region").trim(), accessKeyId, accessKeySecret);
			DefaultAcsClient client = new DefaultAcsClient(profile);
			final AssumeRoleRequest request = new AssumeRoleRequest();
			request.setActionName("AssumeRole");
			request.setVersion(PropertiesService.getString("oss.stsApiVersion").trim());
			request.setMethod(MethodType.POST);
			request.setProtocol(protocolType);
			request.setDurationSeconds((long) PropertiesService.getInteger("oss.tokenLiveSecond",3600));
			request.setRoleArn(roleArn);
			request.setRoleSessionName(roleSessionName);
			request.setPolicy(policy);
			
			
			AssumeRoleResponse response =  client.getAcsResponse(request);
			return response;
		
	}
	
}